<template>
  <div>
    <!--==================================搜索栏=====================================-->

    <el-card shadow="never" class="search-card">
      <el-row :gutter="20" class="el-row">
        <el-col class="button-box" :span="4">
          <el-input
            v-model="queryVo.query.queryInfo"
            size="small"
            class="search-input"
            placeholder="请输入搜索内容"
            clearable
            @clear="handleClear('queryInfo')"
          />
        </el-col>
        <el-col class="button-box" :span="4.5">
          <div>
            手机号：
            <el-input
              v-model="queryVo.query.phone"
              size="small"
              class="search-input"
              placeholder="请输入搜索内容"
              clearable
              @clear="handleClear('phone')"
            />
          </div>

        </el-col>
        <el-col class="button-box" :span="5" />

        <el-col class="button-box" :span="6">
          <div>
            学生状态：
            <el-select
              v-model="tempData.tempStatusList"
              size="small"
              class="selector"
              multiple
              clearable
              value-key="label"
              placeholder="请选择"
              @clear="handleClear('statusList')"
              @change="updateStatusList"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

        </el-col>
        <el-col :offset="3" :span="5">
          <div style="float: right">
            <el-button
              size="small"
              type="primary"
              plain
              @click="handleSearch"
            >搜索</el-button>

            <el-button
              size="small"
              type="primary"
              plain
              @click="resetQueryParams"
            >重置</el-button>

            <el-button
              size="small"
              type="primary"
              plain
              @click="unfold = !unfold"
            >{{ unfold == false ? '更多' : '收起' }}</el-button>

          </div>

        </el-col>
      </el-row>
      <el-row v-if="unfold" :gutter="20" class="extend-row">
        <el-col class="button-box" :span="6">
          <div>
            年级：
            <el-select
              v-model="tempData.tempGrade"
              size="small"
              class="unit-selector"
              clearable
              value-key="name"
              placeholder="请选择"
              @clear="handleGradeOrCollegeClear('grade')"
              @change="handleSelectGrade"
            >
              <el-option
                v-for="item in gradeList"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </div>
        </el-col>
        <el-col class="button-box" :span="4.5">
          <div>
            学院：
            <el-select
              v-model="tempData.tempCollege"
              size="small"
              class="unit-selector"
              clearable
              value-key="name"
              placeholder="请选择"
              @clear="handleGradeOrCollegeClear('college')"
              @change="handleSelectCollege"
            >
              <el-option
                v-for="item in collegeList"
                :key="item.name"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </div>

        </el-col>
        <el-col class="button-box" :span="4.5">
          <div>
            专业：
            <el-select
              v-model="tempData.tempMajor"
              size="small"
              class="unit-selector"
              clearable
              value-key="name"
              placeholder="请选择"
              @clear="handleMajorClear"
              @change="handleMajorQuery"
            >
              <el-option
                v-for="item in majorList"
                :key="item.name"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </div>

        </el-col>
        <el-col class="button-box" :span="5" />

        <el-col class="button-box" :span="6">
          <div>
            <div>
              班级：
              <el-select
                v-model="tempData.tempClazz"
                size="small"
                class="unit-selector"
                clearable
                value-key="name"
                placeholder="请选择"
                @clear="handleClear('clazz')"
              >
                <el-option
                  v-for="item in clazzList"
                  :key="item.name"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </div>
          </div>

        </el-col>

      </el-row>
    </el-card>

    <!--==================================END=====================================-->

    <!--==================================表格=====================================-->

    <el-card shadow="never" class="device-table-card">
      <el-button
        size="small"
        type="primary"
        @click="handleCreate"
      >添加学生</el-button>
      <el-table
        ref="filterTable"
        :data="studentList"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="学号"
          width="100"
        />
        <el-table-column
          prop="name"
          label="名字"
          width="100"
        />
        <el-table-column
          prop="grade"
          label="年级"
          width="100"
        />

        <el-table-column
          prop="college"
          label="学院"
          width="100"
        />

        <el-table-column
          prop="major"
          label="专业"
          width="100"
        />

        <el-table-column
          prop="clazz"
          label="班级"
          width="100"
        />

        <el-table-column
          prop="phone"
          label="手机号"
          width="180"
        />

        <el-table-column
          prop="status"
          label="实验权限"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'primary' : 'success'"
              disable-transitions
            >
              {{ scope.row.status === 1 ? "有权" : "无权" }}
            </el-tag>

          </template>
        </el-table-column>

        <el-table-column width="250" fixed="right" label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <!-- 删除 -->
            <el-button type="danger" size="mini" @click="handleDeleteStudent(scope.row.id)">删除</el-button>

            <!--            <el-button type="warning" size="mini" >设置权限</el-button>-->

          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="queryVo.pageNum"
        :page-sizes="[1, 2, 5, 100]"
        :page-size="queryVo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!--==================================END=====================================-->

    <!--==================================表单=====================================-->

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
    >
      <el-form
        ref="dataForm"
        :rules="formRules"
        :model="temp"
        label-width="80px"
      >

        <el-form-item prop="id" label="学号">
          <el-input v-model="temp.id" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="name" label="姓名">
          <el-input v-model="temp.name" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="phone" label="手机号">
          <el-input v-model="temp.phone" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="grade" label="年级">
          <el-select
            v-model="tempData.tempGrade"
            size="small"
            class="unit-selector"
            clearable
            value-key="name"
            placeholder="请选择"
            @clear="handleGradeOrCollegeClear('grade')"
            @change="handleGradeInForm"
          >
            <el-option
              v-for="item in gradeList"
              :key="item.name"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="college" label="学院">
          <el-select
            v-model="tempData.tempCollege"
            size="small"
            class="unit-selector"
            clearable
            value-key="name"
            placeholder="请选择"
            @clear="handleGradeOrCollegeClear('college')"
            @change="handleCollegeInForm"
          >
            <el-option
              v-for="item in collegeList"
              :key="item.name"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="major" label="专业">
          <el-select
            v-model="tempData.tempMajor"
            size="small"
            class="unit-selector"
            clearable
            value-key="name"
            placeholder="请选择"
            @clear="handleClear('major')"
            @change="handleMajorInForm"
          >
            <el-option
              v-for="item in majorList"
              :key="item.name"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="clazz" label="班级">
          <el-select
            v-model="tempData.tempClazz"
            size="small"
            style="width: 300px"
            clearable
            value-key="name"
            placeholder="请选择"
            @clear="handleClear('clazz')"
            @change="handleClazzInForm"
          >
            <el-option
              v-for="item in clazzList"
              :key="item.name"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="temp.status" size="medium">
            <el-radio border :label="1">有权</el-radio>
            <el-radio border :label="0">无权</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleFormClose">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createStudent():updateStudent()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!--==================================END=====================================-->

  </div>
</template>

<script>

import { addStudent, deleteStudent, getStudentList, updateStudent } from '@/api/student'
import { getGradeList } from '@/api/grade'
import { getMajorList } from '@/api/major'
import { getClazzList } from '@/api/clazz'
import { getCollegeList } from '@/api/college'

export default {
  name: 'StudentTable',
  data() {
    return {
      unfold: false,

      totalCount: 5,
      queryVo: {
        query: {
          queryInfo: null,
          id: null,
          name: null,
          grade: null,
          gradeId: null,
          college: null,
          collegeId: null,
          major: null,
          majorId: null,
          clazz: null,
          clazzId: null,
          phone: null,
          statusList: null
        },
        pageNum: 1,
        pageSize: 5
      },
      temp: {
        id: null,
        name: null,
        grade: null,
        college: null,
        major: null,
        clazz: null,
        phone: null,
        status: null
      },
      // 保存搜索和表单的年级、学院、专业、班级、状态JSON对象，用于级联查找
      tempData: {

        tempGrade: {},

        tempCollege: {},

        tempMajor: {},

        tempClazz: {},

        tempStatusList: []
      },

      studentList: [],

      gradeList: [],

      collegeList: [],

      majorList: [],

      clazzList: [],

      statusOptions: [{
        label: '无权',
        value: 0
      },
      {
        label: '有权',
        value: 1
      }
      ],

      textMap: {
        update: '修改',
        create: '添加'
      },

      dialogFormVisible: false,

      dialogStatus: '',

      formRules: {
        id: [
          { required: true, message: '请输入学号', trigger: 'blur' }

        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }

        ],
        phone: [
          {
            pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          },
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
          }
        ],
        grade: [
          { required: true, message: '请输入年级', trigger: 'blur' }

        ],
        major: [
          { required: true, message: '请输入专业', trigger: 'blur' }

        ],
        clazz: [
          { required: true, message: '请输入班级', trigger: 'blur' }

        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }

        ]
      }
    }
  },

  watch: {

    'tempData.tempStatusList'(val) {
      if (typeof (val) !== 'undefined' && val.length === 0) {
        this.queryVo.query.statusList = null
      }
    }
  },

  mounted() {
    getStudentList(this.queryVo).then(response => {
      this.studentList = response.data.list
      this.totalCount = response.data.total
    })

    getGradeList(this.queryVo).then(response => {
      this.gradeList = response.data.list
    })

    getCollegeList(this.queryVo).then(response => {
      this.collegeList = response.data.list
    })
  },
  methods: {

    /* ==========================================搜索相关===================================================*/

    handleClear(queryParam) {
      this.queryVo.query[queryParam] = null
    },

    handleGradeOrCollegeClear(param) {
      console.log(param)
      this.handleClear(param)
      this.tempData.tempMajor = null
      this.tempData.tempClazz = null

      this.majorList = []
      this.clazzList = []
    },

    handleMajorClear() {
      this.handleClear('major')
      this.tempData.tempClazz = null
      this.clazzList = []
    },

    handleSearch() {
      getStudentList(this.queryVo).then(response => {
        this.studentList = response.data.list
        this.totalCount = response.data.total
      })
    },

    queryMajorByGrade(grade) {
      if (typeof (grade) === 'object') {
        console.log(' queryMajorByGrade被调用')
        this.queryVo.query.gradeId = grade.id
        this.queryVo.query.grade = grade.name
        this.getMajor()
      }
    },

    queryMajorByCollege(college) {
      if (typeof (college) === 'object') {
        this.queryVo.query.collegeId = college.id
        this.queryVo.query.college = college.name
        this.getMajor()
      } else {
        this.getMajor()
      }
    },

    handleSelectGrade(grade) {
      this.handleGradeOrCollegeClear('grade')
      this.queryMajorByGrade(grade)
    },
    handleSelectCollege(college) {
      this.handleGradeOrCollegeClear('college')
      this.queryMajorByCollege(college)
    },

    handleMajorQuery(major) {
      if (typeof (major) === 'object') {
        this.queryVo.query.majorId = major.id
        this.queryVo.query.major = major.name

        this.getClazz()
      } else {
        this.tempData.tempClazz = null
        this.clazzList = []
      }
    },

    getMajor() {
      getMajorList(this.queryVo).then(response => {
        this.majorList = response.data.list
      })
    },

    getClazz() {
      getClazzList(this.queryVo).then(response => {
        this.clazzList = response.data.list
      })
    },

    resetQueryVo() {
      this.queryVo.query = {
        queryInfo: null,
        id: null,
        name: null,
        grade: null,
        gradeId: null,
        major: null,
        majorId: null,
        clazz: null,
        clazzId: null,
        phone: null,
        statusList: null
      }
    },

    resetTempData() {
      this.tempData = {
        tempGrade: {},

        tempMajor: {},

        tempClazz: {}
      }
      this.tempStatusList = []
    },

    resetQueryParams() {
      this.resetQueryVo()
      this.resetTempData()
    },

    updateStatusList() {
      this.queryVo.query.statusList = this.tempData.tempStatusList
    },

    /* ==========================================END===================================================*/

    /* ==========================================表单相关===================================================*/

    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        college: '',
        grade: '',
        major: '',
        clazz: '',
        phone: '',
        status: ''
      }
    },

    handleGradeInForm(grade) {
      this.temp.grade = grade.name
      this.handleSelectGrade(grade)
    },

    handleCollegeInForm(college) {
      this.temp.college = college.name
      this.handleSelectCollege(college)
    },

    handleMajorInForm(major) {
      this.temp.major = major.name
      this.handleMajorQuery(major)
    },

    handleClazzInForm(clazz) {
      this.temp.clazz = clazz.name
    },

    handleFormClose() {
      this.resetQueryVo()
      this.resetTempData()
      this.dialogFormVisible = false
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createStudent() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addStudent(this.temp).then(() => {
            this.resetQueryVo()
            this.resetTempData()

            getStudentList(this.queryVo).then(response => {
              this.studentList = response.data.list
              this.totalCount = response.data.total
            })

            this.dialogFormVisible = false

            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    initFormTempData(row) {
      this.tempData.tempClazz.name = row.clazz

      this.collegeList.forEach(college => {
        if (college.name === row.college) {
          this.tempData.tempCollege = college
          this.queryVo.query.collegeId = college.id
        }
      })

      this.gradeList.forEach(grade => {
        if (grade.name === row.grade) {
          this.tempData.tempGrade = grade
          this.queryVo.query.gradeId = grade.id
          getMajorList(this.queryVo).then(res => {
            this.majorList = res.data.list
            this.majorList.forEach(major => {
              if (major.name === row.major) {
                this.tempData.tempMajor = major
                this.queryVo.query.majorId = major.id
                getClazzList(this.queryVo).then(response => {
                  this.clazzList = response.data.list
                  this.clazzList.forEach(clazz => {
                    if (clazz.name === row.clazz) {
                      this.tempData.tempClazz = clazz
                    }
                  })
                })
              }
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj

      this.initFormTempData(row)

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateStudent() {
      this.resetQueryVo()

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateStudent(tempData).then(() => {
            this.resetTempData()

            getStudentList(this.queryVo).then(response => {
              this.studentList = response.data.list
              this.totalCount = response.data.total
            })

            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDeleteStudent(sid) {
      this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStudent(sid).then(() => {
          getStudentList(this.queryVo).then(response => {
            this.studentList = response.data.list
            this.totalCount = response.data.total
          })

          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /* ==========================================END===================================================*/

    /* ==========================================分页相关===================================================*/

    handleSizeChange(newSize) {
      this.queryVo.pageSize = newSize
      getStudentList(this.queryVo).then(response => {
        this.studentList = response.data.list
        this.totalCount = response.data.total
      })
    },
    handleCurrentChange(newSize) {
      this.queryVo.pageNum = newSize
      getStudentList(this.queryVo).then(response => {
        this.studentList = response.data.list
        this.totalCount = response.data.total
      })
    }

    /* ==========================================END===================================================*/

  }

}
</script>

<style scoped>
.search-input {
  width: 150px;
}
.selector {
  width: 130px;
}
.search-card {
  font-size: 15px;
}
.extend-row{
  margin-top: 10px;
}
</style>
